<template>
    <div class="musical-score-container">
        <div class="score-display">
            <div ref="scoreContainer" class="score-container">
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import abcjs from 'abcjs'
import 'abcjs/abcjs-audio.css'



// Props定义
const props = defineProps({
  notation: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: '乐谱显示'
  },
  autoRender: {
    type: Boolean,
    default: true
  },
  showControls: {
    type: Boolean,
    default: true
  }
})


const scoreContainer = ref(null)
const ABCJS = abcjs


const hasNotation = computed(() => props.notation && props.notation.trim().length > 0)

// 方法
const checkLibrary = () => {
    if (!ABCJS) {
        console.log('❌ ABCJS 库未加载')
        return
    }
    if (!ABCJS.renderAbc) {
        console.log('❌ ABCJS.renderAbc 不可用')   
        return
    }
    console.log(`✅ ABCJS 已加载`)

}


// 渲染从props传入的乐谱
const renderFromProps = () => {
    if (!hasNotation.value) {
        showError('没有传入乐谱代码')
        return
    }

    clearScore()
    
    try {
        console.log('开始渲染传入的乐谱:', props.notation)
        
        const visualObj = renderScore(props.notation, {
            responsive: 'resize',
            add_classes: true,
            scale: 1.2,
            staffwidth: 560,
            format: {
                stretchlast: true,
                vocalfont: "16px Arial",
                annotationfont: "bold 14px Arial"
            },
            paddingbottom: 30,
            paddingTop: 30
        })
        console.log('乐谱渲染结果:', visualObj)
        
        if (visualObj && visualObj.length > 0) {
            console.log('乐谱渲染成功')
        } else {
            console.error('乐谱渲染失败')
            showError('乐谱渲染失败')
        }
    } catch (error) {
        console.error('乐谱渲染错误:', error)
        showError('乐谱渲染失败: ' + error.message)
    }
}

const renderScore = (notation, options = {}) => {
    const container = scoreContainer.value
    try {
        const visualObj = ABCJS.renderAbc(container, notation, options)
        console.log('乐谱渲染结果:', visualObj)
        return visualObj
    } catch (error) {
        showError('渲染失败: ' + error.message)
        return null
    }
}


const clearScore = () => {
    const container = scoreContainer.value
    if (container) {
        container.innerHTML = ''
    }
}

const showError = (message) => {
    console.log(message)
}



// 监听props变化
watch(() => props.notation, (newNotation) => {
    if (newNotation && props.autoRender) {
        setTimeout(() => {
            renderFromProps()   
        }, 500)
    }
}, { immediate: true })

// 生命周期
onMounted(() => {
    checkLibrary()
})
</script>

<style scoped>

</style>